/**
 * Created on 2020-6-28
 * Last editor on 2020-6-28
 * @author: guixin
 */
package com.example.auv_660.order;

import com.example.auv_660.MainActivity;
import com.example.auv_660.autocontrolalgorithm.assistantsensor.BatterySensor;
import com.example.auv_660.autocontrolalgorithm.assistantsensor.LocationSensor;
import com.example.auv_660.autocontrolalgorithm.assistantsensor.OrientationSensor;
import com.example.auv_660.autocontrolalgorithm.assistantsensor.SpeedSensor;
import com.example.auv_660.network.udp.HFUDPBuild;
import com.example.auv_660.util.Constants;
import com.example.auv_660.util.MsgType;

import org.json.JSONException;
import org.json.JSONObject;

public class SendReceiveOrder {
    public static int heartBeatCount = 1;
    public static int receivedHeartBeatCount = 1;
    public static MainActivity mainActivity = MainActivity.getInstance();

    /**
     * 设备初始化
     */
    public static void deviceInit()
    {
        new Thread(new Runnable()
        {
            @Override
            public void run()
            {
                while (true)
                {
                    try
                    {
                        registerHeartBeat(5000);
                        uploadInformation();
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();
    }

    /**
     * 定时发送设备信息
     * @throws JSONException
     */
    public static void uploadInformation() throws JSONException
    {
        Information information = new Information();

        LocationSensor ls = new LocationSensor();
        information.setLocationValue(ls.getValue("SCREEN"));

        BatterySensor batterySensor = new BatterySensor();
        information.setPhoneBatteryValue(batterySensor.getCurrentBattery());

        information.setOrientationValue(OrientationSensor.getInstance().getValue());

        information.setSpeedValue(SpeedSensor.getInstance().getValue());

        JSONObject InformationJson = OrderJson.CreateInformationJson(information);

        String content = OrderJson.CreateOrderJson(Constants.PHONEIMEI, OrderJson.INFORMATION_ORDER,
                InformationJson.toString());
        HFUDPBuild.INSTANCE.getHFUdpClient().sendMessage(content);

        if (mainActivity != null)
        {
            mainActivity.updateAttitudeData(information.getOrientationValue());
        }
    }

    /**
     * 定时发送心跳包
     * @param internal
     * @throws JSONException
     */
    public static void registerHeartBeat(int internal) throws JSONException
    {
        String content = OrderJson.CreateOrderJson(Constants.PHONEIMEI, OrderJson.HEARTBEAT_ORDER,
                heartBeatCount++ + "");
        try
        {
            Thread.sleep(internal);
            HFUDPBuild.INSTANCE.getHFUdpClient().sendMessage(content);
            Thread.sleep(1000);
            if (mainActivity != null)
            {
                if (heartBeatCount - 5 > receivedHeartBeatCount)
                {
                    mainActivity.sendMsgToMainThread(MsgType.CONTROLLER_CONN, "连接已丢失");
                    heartBeatCount = 1;
                    receivedHeartBeatCount = 1;
                }
                mainActivity.sendMsgToMainThread(MsgType.WHITE_HEART, "");
            }
        }
        catch (InterruptedException e)
        {
            e.printStackTrace();
        }
    }

    /**
     * 接收命令
     * @param order
     */
    public static void receiveOrder(String order)
    {
        try
        {
            JSONObject json_str = new JSONObject(order);
            // AUVID为本设备
            if (json_str.getString(OrderJson.AUVID).equals(Constants.PHONEIMEI))
            {
                // 心跳命令
                if (json_str.getString(OrderJson.ORDER).equals(OrderJson.HEARTBEAT_ORDER))
                {
                    receivedHeartBeatCount = Integer.parseInt(json_str.getString(OrderJson.CONTENT));
                    if (mainActivity != null)
                    {
                        mainActivity.sendMsgToMainThread(MsgType.CONTROLLER_CONN, "心跳包 " + json_str.getString(OrderJson.CONTENT));
                        mainActivity.sendMsgToMainThread(MsgType.RED_HEART, "");
                    }
                }
                // 查询信息命令
                else if (json_str.getString(OrderJson.ORDER).equals(OrderJson.INFORMATION_ORDER))
                {

                }
                // 自检命令
                else if (json_str.getString(OrderJson.ORDER).equals(OrderJson.SELFCHECKING_ORDER))
                {

                }
                // 制动命令
                else if (json_str.getString(OrderJson.ORDER).equals(OrderJson.BRAKING_ORDER))
                {

                }
                // 遥控命令
                else if (json_str.getString(OrderJson.ORDER).equals(OrderJson.REMOTECONTROL_ORDER))
                {

                }
                // 直航命令
                else if (json_str.getString(OrderJson.ORDER).equals(OrderJson.DIRECTROUTE_ORDER))
                {

                }
                // 导航命令
                else if (json_str.getString(OrderJson.ORDER).equals(OrderJson.NAVIGATION_ORDER))
                {

                }
                // 返航命令
                else if (json_str.getString(OrderJson.ORDER).equals(OrderJson.COURSEREVERSAL_ORDER))
                {

                }
                else
                {

                }

            }
        }
        catch (JSONException e)
        {
            e.printStackTrace();
        }

        //                            if (order.contains("TASKINFO"))
//                            {
//                                TaskUtils taskUtils = new TaskUtils();
//                                taskUtils.writeTask(order.substring(9));
//                                taskUtils.realseWriteTask();
//                            }
//                            else if (order.contains("stop"))
//                            {
//                                if (mainActivity != null)
//                                {
//                                    mainActivity.sendMsgToMainThread(MsgType.CONTROLLER_MSG, "制动停车");
//                                    mainActivity.sendMsgToMainThread(MsgType.RED_SHA_CHE, "");
//                                    Constants.RUN = false;
//                                }
//                            }
//                            else if (order.contains("innerdata"))
//                            {
//                                System.out.println(receiveData.getAddress().getHostAddress());
//                                File fileDATA = null;
//                                if (order.contains("DS"))
//                                {
//                                    fileDATA = new File(Constants.FILE_PATH + Constants.DS);
//                                }
//                                else
//                                {
//                                    fileDATA = new File(Constants.FILE_PATH + Constants.DH);
//                                }
//                                File[] files = fileDATA.listFiles();
//
//                                InetAddress ip = receiveData.getAddress();
//                                int port = receiveData.getPort();
//
//                                if (files.length != 0)
//                                {
//                                    for (File file : files)
//                                    {
////                                        sendMessage(file.getName(), ip, port);
//                                        try
//                                        {
//                                            BufferedReader br = new BufferedReader(new FileReader(file));
//                                            String s = br.readLine();
//                                            while (null != s)
//                                            {
////                                                sendMessage(s, ip, port);
//                                                s = br.readLine();
//                                            }
////                                            sendMessage("end", ip, port);
//                                            br.close();
//                                        }
//                                        catch (FileNotFoundException e)
//                                        {
//                                            e.printStackTrace();
//                                        }
//                                        catch (IOException e)
//                                        {
//                                            e.printStackTrace();
//                                        }
//                                        System.out.println(file.getName() + " done");
//                                        file.delete();
//                                    }
//                                }
//                            }
//                            else if (order.contains("PCTEST"))
//                            {
//                                System.out.println("**********" + order);
//                                if (order.contains("start"))
//                                {
//                                    try
//                                    {
//                                        bw = new BufferedWriter(new FileWriter(new File(Constants.FILE_PATH + "TEST/" + "test.txt")));
//                                    }
//                                    catch (IOException e)
//                                    {
//                                        e.printStackTrace();
//                                    }
//                                }
//                                else if (order.contains("end"))
//                                {
//                                    try
//                                    {
//                                        bw.close();
//                                    }
//                                    catch (IOException e)
//                                    {
//                                        e.printStackTrace();
//                                    }
//                                    bw = null;
//                                }
//                                else
//                                {
//                                    try
//                                    {
//                                        bw.write(order.split("-")[1] + "\n");
//                                    }
//                                    catch (IOException e)
//                                    {
//                                        e.printStackTrace();
//                                    }
//                                }
//                            }
//                            else if (order.contains("GETTESTDATANAME"))
//                            {
//                                File ds = new File(Constants.FILE_PATH + Constants.DS);
//                                File dh = new File(Constants.FILE_PATH + Constants.DH);
//                                String[] dsFileName = ds.list();
//                                String[] dhFileName = dh.list();
//                                StringBuilder sb = new StringBuilder();
//                                if (dsFileName != null)
//                                {
//                                    for (String name : dsFileName)
//                                    {
//                                        sb.append(name + ",");
//                                    }
//                                }
//
//                                if (dhFileName != null)
//                                {
//                                    for (String name : dhFileName)
//                                    {
//                                        sb.append(name + ",");
//                                    }
//                                }
//                                String message = "C" + Constants.PHONEIMEI + "," + sb.toString();
//                                System.out.println("filename: " + message);
////                                HFUDPBuild.INSTANCE.getHFUdpClient().sendMessage(message);
//                            }
//                            else if (order.contains("TCPGET"))
//                            {
//                                System.out.println("TCP order: " + order);
//                                Socket socket = null;
//                                try
//                                {
//                                    socket = new Socket(Constants.SERVER_IP, Constants.TCP_SERVER_PORT);
//                                }
//                                catch (IOException e)
//                                {
//                                    e.printStackTrace();
//                                }
//                                DataOutputStream pw = null;
//                                try
//                                {
//                                    pw = new DataOutputStream(socket.getOutputStream());
//                                }
//                                catch (IOException e)
//                                {
//                                    e.printStackTrace();
//                                }
//                                String fileName = order.split(",")[1];
//                                File file = null;
//                                String path = null;
//                                if (fileName.contains("DH"))
//                                {
//                                    path = Constants.FILE_PATH + Constants.DH + fileName;
//                                }
//                                else
//                                {
//                                    path = Constants.FILE_PATH + Constants.DS + fileName;
//                                }
//                                file = new File(path);
//
//                                if (file.exists())
//                                {
//                                    try
//                                    {
//                                        BufferedReader br = new BufferedReader(new FileReader(file));
//                                        pw.writeUTF(file.getName());
//                                        String line = br.readLine();
//                                        while (line != null) {
//                                            System.out.println("line: " + line);
//                                            pw.writeUTF(line);
//                                            line = br.readLine();
//                                        }
//                                        pw.writeUTF("END");
//                                        br.close();
//                                        pw.close();
//                                    }
//                                    catch (FileNotFoundException e)
//                                    {
//                                        e.printStackTrace();
//                                    }
//                                    catch (IOException e)
//                                    {
//                                        e.printStackTrace();
//                                    }
//                                }
//                                if (socket != null)
//                                {
//                                    try
//                                    {
//                                        socket.close();
//                                        socket = null;
//                                    }
//                                    catch (IOException e)
//                                    {
//                                        e.printStackTrace();
//                                    }
//                                }
//                            }
//                            else
//                            {
//                                if (Constants.ORDER)
//                                {
//                                    FileUtils.INSTANCE.getFileWrite().writeCMD(Tools.DateFormat(new Date(), "S") + "," + order + "\n");
//                                    if (mainActivity != null)
//                                    {
//                                        mainActivity.sendMsgToMainThread(MsgType.WHITE_NORMAL, "");
//                                    }
//                                    instances.get(0).doOrder(order);
//                                }
//                            }
//                            receiveData.setLength(BUFFER_LENGTH);
    }
}
